<template>
  <el-dialog :visible.sync="selectImgVisible" width="48%" :before-close="handleClose">
    <div class="dialog-content" v-loading="loading">
      <el-tabs v-model="activeName">
        <el-tab-pane label="上传图片" name="first">
          <div class="tabs-first">
            <div class="center-btn">
              <el-upload
                ref="upload"
                accept="image/*"
                action="//suhao.online:8001"
                :multiple="bannerNum == 3"
                :limit="3"
                :on-exceed="onExceed"
                :before-upload="beforeUpload"
                :http-request="customHttpQeq"
                :show-file-list="false"
              >
                <el-button type="danger">选择图片</el-button>
              </el-upload>
              <p class="btn-tip">支持jpg、jpeg、png等多种格式，单张图片最大支持10MB</p>
            </div>
            <div class="recommend">
              <template>
                为你的文章智能匹配免费正版图片
                <span class="float-more" @click="handleClick">
                  查看更多
                  <svg class="byte-icon" viewBox="0 0 1024 1024" width="1em" height="1em" fill="currentColor">
                    <path
                      d="M630.4 512L283.52 165.12a21.12 21.12 0 010-30.08l30.08-30.08a21.12 21.12 0 0130.08 0l377.6 376.96a42.24 42.24 0 010 60.16l-377.6 376.96a21.12 21.12 0 01-30.08 0l-30.08-30.08a21.12 21.12 0 010-30.08z"
                    ></path></svg
                ></span>
              </template>
              <div class="recommend-wrapper">
                <ul class="ul-card">
                  <li class="recommend-ul-li" v-for="item in wrapperList20" :key="item.key" @click="$emit('select-recommend-img', item)">
                    <img :src="item" alt="" />
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="免费正版图片" name="second">
          <div class="tabs-second">
            <div class="content-scorll" id="infiniteScroll">
              <ul class="ul-list">
                <li
                  class="more-ul-li"
                  :style="{ backgroundImage: 'url(' + item + ')' }"
                  v-for="(item, index) in wrapperList"
                  :key="item.key"
                  @mouseover="imgMouseover(index)"
                  @mouseleave="imgMouseleave()"
                  @click="checkRadio(index, item)"
                >
                  <span class="hover-icon" v-if="currentIdx === index"></span>
                  <span class="pop-number" v-if="computedCheckIdx(index)">{{ radiusNum[index] }}</span>
                  <span class="pop-bg" v-if="computedCheckIdx(index)"></span>
                </li>
              </ul>
            </div>
            <footer class="tip-agree">
              <p class="des">
                使用图库前，请先阅读
                <a style="color:#1356bd" target="_blank" href="https://mp.toutiao.com/profile_v3_public/public/protocol/pic-agreement">
                  《图片许可使用协议》
                </a>
                ，你的使用行为视为你已同意该协议。如不同意，请停止使用图库内容。
              </p>
              <p class="des">图库中的图片仅限在今日头条以编辑发布文章，不得用于其他任何平台和用途</p>
            </footer>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-dialog>
</template>
<script>
import { uploadArticleCover } from './api';
import coverList from './coverUrl.js';

export default {
  props: {
    selectImgVisible: {
      type: Boolean,
      default: false
    },
    bannerNum: {
      type: Number,
      default: 1,
      validator: val => {
        return [1, 3].includes(val);
      }
    }
  },
  data() {
    return {
      loading: false,
      activeName: 'first',
      wrapperList: coverList,
      currentIdx: '',
      selectIdx: [],
      radiusNum: {},
      selectFileList: []
    };
  },
  computed: {
    wrapperList20() {
      return this.wrapperList.filter((item, idx) => {
        return idx < 20;
      });
    }
  },
  watch: {
    selectImgVisible: {
      handler() {
        setTimeout(() => {
          let mdom = document.getElementById('infiniteScroll');
          mdom.addEventListener(
            'scroll',
            this.debounced(() => {
              //文档内容实际高度 - 弹框高度
              var scrollHeight = mdom.scrollHeight - mdom.offsetHeight;
              //滚动条滚动距离
              var scrollTop = mdom.pageYOffset || mdom.scrollTop;
              // 阀值100
              if (scrollHeight - scrollTop < 100) {
                console.log('到底部了');
                this.wrapperList = this.wrapperList.concat([], this.wrapperList);
              }
            }, 300)
          );
        }, 50);
      }
    }
  },
  methods: {
    customHttpQeq(e) {
      let file = e.file;
      let params = new FormData(); // 创建form对象
      params.append('file', file); // 通过append向form对象添加数据
      this.loading = true;
      uploadArticleCover(params).then(res => {
        this.loading = false;
        this.$refs.upload.clearFiles();
        if (res.success) {
          this.$emit('select-recommend-img', res.data.url);
        }
      });
    },
    onExceed(files) {
      if (files.length > 3) {
        this.$message.error('至多只能上传3张图片');
      }
    },
    beforeUpload(file, list) {
      let type = file.type;
      if ((type !== 'image/jpg' && type !== 'image/jpeg' && type !== 'image/png') || file.size / 1024 > 10240) {
        this.$message.error('只能上传jpg/png文件，且不超过10M');
        return false;
      }
      return true;
    },
    computedCheckIdx(idx) {
      return this.selectIdx.includes(idx);
    },
    checkRadio(idx, val) {
      if (this.bannerNum == 1) {
        this.$emit('select-recommend-img', val);
        return;
      }
      if (this.selectIdx.includes(idx)) {
        this.selectIdx.splice(this.selectIdx.indexOf(idx), 1);
        this.selectFileList.splice(this.selectIdx.indexOf(idx), 1);
        delete this.radiusNum[idx];
        return;
      }
      this.selectIdx.push(idx);
      this.selectFileList.push(val);
      this.radiusNum[idx] = this.selectIdx.length;
      if (this.bannerNum == 3 && this.selectIdx.length == 3) {
        this.$emit('select-recommend-img', this.selectFileList);
        this.selectIdx = [];
        this.selectFileList = [];
        this.radiusNum = {};
        return;
      }
    },
    imgMouseover(idx) {
      this.currentIdx = idx;
    },
    imgMouseleave() {
      this.currentIdx = '';
    },
    debounced(fn, wait) {
      let time = null;
      return function() {
        if (time) {
          clearTimeout(time);
        }
        time = setTimeout(() => {
          fn.apply(this, arguments);
        }, wait);
      };
    },
    handleClick() {
      this.activeName = 'second';
    },
    handleClose() {
      this.$emit('closeVisible');
    }
  }
};
</script>
<style lang="scss" scoped>
.dialog-content {
  width: 100%;
  .tabs-first {
    width: 100%;
    .center-btn {
      padding: 128px 0 108px;
      text-align: center;
      .btn-tip {
        margin-top: 18px;
        font-size: 12px;
        color: #999;
      }
    }
    .recommend {
      padding: 0 8px;
      .float-more {
        float: right;
        font-size: 14px;
        color: #666;
        cursor: pointer;
        .byte-icon {
          display: inline-block;
          color: inherit;
          font-style: normal;
          width: 1em;
          height: 1em;
          vertical-align: -2px;
          fill: currentColor;
        }
      }
      .recommend-wrapper {
        margin-top: 16px;
        overflow-y: hidden;
        overflow-x: auto;
        height: 150px;
        width: 100%;
        .ul-card {
          height: 132px;
          text-align: left;
          white-space: nowrap;
          .recommend-ul-li {
            display: inline-block;
            margin-right: 20px;
            img {
              height: 132px;
              width: auto;
              cursor: pointer;
            }
          }
          .recommend-ul-li:last-child {
            margin-right: 0;
          }
        }
      }

      /* 滚动条样式 */
      .recommend-wrapper::-webkit-scrollbar {
        height: 8px;
      }
      .recommend-wrapper::-webkit-scrollbar-thumb {
        box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        border-radius: 6px;
        background: rgba(0, 0, 0, 0.1);
      }
    }
  }
  .tabs-second {
    width: 100%;
    height: 494.5px;
    .content-scorll {
      position: relative;
      overflow-y: auto;
      .ul-list {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-around;
        height: 443.5px;
        .more-ul-li {
          position: relative;
          flex: 0 0 24%;
          height: 132px;
          text-align: center;
          margin: 4px 0;
          background-size: cover;
          cursor: pointer;
          .hover-icon {
            position: absolute;
            width: 22px;
            height: 22px;
            left: 8px;
            top: 8px;
            border-radius: 12px;
            background: #b0b0b0;
            border: 1px solid #fff;
          }
          .pop-number {
            position: absolute;
            left: 7px;
            top: 7px;
            color: #fff;
            background: #ff5e5e;
            width: 24px;
            height: 24px;
            border-radius: 12px;
            font-size: 14px;
            display: flex;
            justify-content: center;
            align-items: center;
          }
          .pop-bg {
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: inline-block;
          }
        }
      }
    }
    .content-scorll::-webkit-scrollbar {
      height: 0;
    }
    .tip-agree {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 52px;
      background: #fff;
      font-size: 12px;
      padding-top: 12px;
      .des {
        height: 20px;
        line-height: 20px;
        color: #999;
        text-align: center;
      }
    }
  }
}
</style>
